package com.wink_172.activity

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.graphics.Typeface
import android.net.http.SslError
import android.os.Build
import android.os.Bundle
import android.text.TextUtils
import android.util.Log
import android.view.KeyEvent
import android.view.ViewGroup
import android.webkit.*
import android.widget.LinearLayout
import androidx.appcompat.app.AlertDialog
import androidx.databinding.DataBindingUtil
import com.adjust.sdk.Adjust
import com.adjust.sdk.AdjustEvent
import com.alibaba.fastjson.JSON
import com.wink_172.commons.databinding.ActivityWebAwardBinding
import com.wink_172.library.R
import com.wink_172.library.activity.SmartActivity
import com.wink_172.library.model.Constants
import com.wink_172.library.utils.CommonUtils
import com.wink_172.library.utils.FileUtil
import com.wink_172.library.view.ActionBarView
import org.xutils.x.task


/**
 * 抽奖页面
 * 抽奖历史页面
 * */
class AwardWebActivity : SmartActivity() {
    lateinit var mWeb: WebView
    lateinit var binding: ActivityWebAwardBinding

    companion object {
        //p133
        fun startActivity(context: Context, vararg args: Any?) {
            val intent = Intent(context, AwardWebActivity::class.java).apply {
                val mode =
                    args[0] as Int

                when (mode) {
                    0 -> {
                        putExtra(Constants.PARAM_DATA1, mode)
                    }

                    else -> {

                    }
                }
            }

            context.startActivity(intent)
        }

        private const val TAG = "AwardWebActivity"
    }


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        binding =
            DataBindingUtil.setContentView(this, com.wink_172.commons.R.layout.activity_web_award)


        initView()

        initWebView()
        init()

    }


    fun initView() {}
    fun init() {
        mode = intent.getIntExtra(Constants.PARAM_DATA1, 0);



        if (true) {


        }
        if (true) {


        }


        when (mode) {
            0 -> {
                (binding!!.actionBar as ActionBarView).background = null
                (binding!!.actionBar as ActionBarView).setLineEnable(false)
                (binding!!.actionBar as ActionBarView).content.setTypeface(Typeface.DEFAULT_BOLD);
                (binding!!.actionBar as ActionBarView).right_text.setTypeface(Typeface.DEFAULT_BOLD);
                (binding!!.actionBar as ActionBarView).updateAllContent(
                    R.mipmap.icon_transparent,
                    "",
                    ""
                );
                (binding!!.actionBar as ActionBarView).setCallback(object :
                    ActionBarView.ICallback {
                    override fun onSendEvent(event: Int, content: String?) {
                        if (event == ActionBarView.LEFT_BTN) {
                            finish()

                        } else if (event == ActionBarView.RIGHT_BTN) {

                        }
                    }
                })

                val token = "OFqsZVh9Mg3bhrn1JjPlCEoAdunBgvT2hE6VKk8foBo="
                var url =
                    "https://gs.hongbaodada.com/experience/0028/zao_lottery/h5_raffle.html?platfom=Android&token=" + token


                url = "https://wsd-demo.netlify.app/app-test"

                url = "https://www.jiliapp2.com/"
//                url = "https://wsd-demo.netlify.app/"
//                url = "https://www.90jilivip.tv/"


//                url="https://www.wjcasino01.com"  //vpn巴西节点
                url="https://jbet77.xyz/"
                Log.e(TAG, "init: ====>>aaa:" + url)
                loadUrl(url)
            }

        }


    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        // Check whether the key event is the Back button and if there's history.
        if (keyCode == KeyEvent.KEYCODE_BACK && mWeb.canGoBack()) {
            mWeb.goBack()
            return true
        }
        // If it isn't the Back button or there isn't web page history, bubble up to
        // the default system behavior. Probably exit the activity.
        return super.onKeyDown(keyCode, event)
    }

    fun testSendMess() {
        val json = com.wink_172.model.Data41()
        json.action = "test"
        mWeb!!.evaluateJavascript("javascript:AndroidCalljs(" + JSON.toJSONString(json) + ")",
            object :
                ValueCallback<String> {
                override fun onReceiveValue(p0: String?) {
                    Log.e(TAG, "onReceiveValue:aaa ====>>" + p0)
                }

            }
        )

    }


    private fun initWebView() {
        mWeb = WebView(this)
        val param = LinearLayout.LayoutParams(
            ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.MATCH_PARENT
        )
        mWeb!!.scrollBarStyle = WebView.SCROLLBARS_OUTSIDE_OVERLAY
        mWeb!!.overScrollMode = WebView.OVER_SCROLL_NEVER
        mWeb!!.setBackgroundColor(resources.getColor(android.R.color.white))
        mWeb!!.layoutParams = param
        binding!!.web.addView(mWeb)
        initWebViewSettings(mWeb!!)
        setWebClientConfig(mWeb!!)
        //        addJsNativeInterface(mWeb);
    }


    @SuppressLint("JavascriptInterface")
    private fun initWebViewSettings(web: WebView) {
        CookieSyncManager.createInstance(this)
        val cm = CookieManager.getInstance()
        cm.setAcceptCookie(true)
        val settings = web.settings
        settings.setSupportZoom(true)
        settings.builtInZoomControls = false
        settings.javaScriptEnabled = true//在 WebView 中使用 JavaScript
        settings.domStorageEnabled = true
        settings.databaseEnabled = true
        settings.useWideViewPort = true
        settings.javaScriptCanOpenWindowsAutomatically = true
        settings.loadWithOverviewMode = true
//        settings.setUserAgentString(CommonJavaUtils.getUseragent(activity));  //暂定
        web.addJavascriptInterface(WebAppInterface(this), "Android")
        //在开发专为 Android 应用中的 WebView 设计的 Web 应用时，您可以在 JavaScript 代码和客户端 Android 代码之间创建接口。
        // 例如，您的 JavaScript 代码可以调用 Android 代码中的方法（而不是使用 JavaScript 的 alert() 函数）来显示 Dialog。
        //如需绑定 JavaScript 和 Android 代码之间的新接口，请调用 addJavascriptInterface()，
        //并向其传递一个类实例以绑定到您的 JavaScript，以及一个接口名称，以供 JavaScript 调用以访问该类。

        settings.cacheMode = WebSettings.LOAD_DEFAULT
        val cache = FileUtil.getAppFilesDir("cache")
        val cachePath = if (cache != null && cache.exists()) cache.path else cacheDir.path
        settings.databasePath = cachePath


        web.webChromeClient = //在加载网页前加上这句就可以了
            object :
                WebChromeClient() {
                override fun onJsAlert(
                    view: WebView?,
                    url: String?,
                    message: String?,
                    result: JsResult?
                ): Boolean {
                    return super.onJsAlert(view, url, message, result)
                    //true，拦截JavaScript的弹窗。如果拦截了，不会出现弹窗。
                    //false，不拦截JavaScript的弹窗，由WebView自行决定弹窗。
//                    if(result!=null){
//                        result.cancel()
//                    }
//
//                    Log.e(TAG, "onJsAlert: ====>>aaa  "+message )
//                    var msg = if (TextUtils.isEmpty(message)) {
//                        ""
//                    } else {
//                        message!!
//                    }
//                    DialogUtils.showSingleBtnDialog2(activity, msg, "我知道了", null)

//                    return true
                }

                override fun onJsConfirm(
                    view: WebView?,
                    url: String?,
                    message: String?,
                    result: JsResult?
                ): Boolean {
                    Log.e(TAG, "onJsConfirm: ====>>aaa  " + message)
                    return super.onJsConfirm(view, url, message, result)
                }

                override fun onJsPrompt(
                    view: WebView?,
                    url: String?,
                    message: String?,
                    defaultValue: String?,
                    result: JsPromptResult?
                ): Boolean {
                    Log.e(TAG, "onJsPrompt: ====>>aaa  " + message)
                    return super.onJsPrompt(view, url, message, defaultValue, result)
                }

                override fun onJsBeforeUnload(
                    view: WebView?,
                    url: String?,
                    message: String?,
                    result: JsResult?
                ): Boolean {
                    Log.e(TAG, "onJsBeforeUnload: ====>>aaa  " + message)
                    return super.onJsBeforeUnload(view, url, message, result)
                }

                override fun onConsoleMessage(consoleMessage: ConsoleMessage): Boolean {
//打印控制台消息
                    Log.e(
                        "MyApplication", "${consoleMessage.message()} ==== From line " +
                                "${consoleMessage.lineNumber()} of ${consoleMessage.sourceId()}"
                    )


                    return super.onConsoleMessage(consoleMessage)
                }
            }

    }


    private fun setWebClientConfig(view: WebView) {
        view.webViewClient = object : WebViewClient() {


            override fun shouldInterceptRequest(
                view: WebView?,
                request: WebResourceRequest?
            ): WebResourceResponse? {
                return super.shouldInterceptRequest(view, request)
            }

            override fun shouldOverrideKeyEvent(view: WebView?, event: KeyEvent?): Boolean {
                return super.shouldOverrideKeyEvent(view, event)
            }

            override fun shouldOverrideUrlLoading(
                view: WebView?,
                request: WebResourceRequest?
            ): Boolean {
                return super.shouldOverrideUrlLoading(view, request)
            }

            override fun shouldOverrideUrlLoading(view: WebView, url: String): Boolean {
                if (!TextUtils.isEmpty(url) && url.startsWith(WebView.SCHEME_TEL)) {
                    return true
                }
                view.loadUrl(url)
                return true
            }

            //            override fun onPageStarted(view: WebView, url: String, favicon: Bitmap) {}
            override fun onPageFinished(view: WebView, url: String) {
                Log.e(TAG, "onPageFinished: aaa====>>")
//                view.loadUrl("javascript:AndroidCalljs()");

            }

            override fun onReceivedSslError(
                view: WebView,
                handler: SslErrorHandler,
                error: SslError
            ) {
                showSslError(handler, error)
            }
        }
        view.webChromeClient = object : WebChromeClient() {
            override fun onReceivedTitle(view: WebView, title: String) {
                Log.e(TAG, "onReceivedTitle:aaa ====>>" + title)
                if (view.canGoBack()) {
                }
            }

            override fun onProgressChanged(view: WebView, newProgress: Int) {}
        }
        try {
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1) {
                view.removeJavascriptInterface("searchBoxJavaBridge_")
                view.removeJavascriptInterface("accessibility")
                view.removeJavascriptInterface("accessibilityTraversal")
            }
        } catch (e: Exception) {
        }
    }

    /**
     * 谷歌上架必须要调用该方法
     */
    private fun showSslError(handler: SslErrorHandler, error: SslError) {
        val builder = AlertDialog.Builder(this@AwardWebActivity)
        var message = "SSL Certificate error."
        val bb = error.primaryError
        message = when (bb) {
            SslError.SSL_UNTRUSTED -> "The certificate authority is not trusted."
            SslError.SSL_EXPIRED -> "The certificate has expired."
            SslError.SSL_IDMISMATCH -> "The certificate Hostname mismatch."
            SslError.SSL_NOTYETVALID -> "The certificate is not yet valid."
            SslError.SSL_DATE_INVALID -> "The date of the certificate is invalid"
            SslError.SSL_INVALID -> "A generic error occurred"
            else -> "A generic error occurred"
        }
        message += " Do you want to continue anyway?"
        builder.setTitle("SSL Certificate Error")
        builder.setMessage(message)
        builder.setPositiveButton("Continue") { dialog, which -> handler.proceed() }
        builder.setNegativeButton("Cancel") { dialog, which -> handler.cancel() }
        val dialog = builder.create()
        dialog.show()
    }

    private fun loadUrl(href: String?) {
        if (!TextUtils.isEmpty(href)) {
            try {
                Log.e(TAG, "web 加载的链接 $href")
                mWeb!!.loadUrl(href!!)
            } catch (e: Exception) {
            }
        }
    }

    public override fun onDestroy() {
        super.onDestroy()
        if (binding!!.web != null) {
            binding!!.web.removeView(mWeb)
        }
        mWeb!!.stopLoading()
        mWeb!!.clearHistory()
        mWeb!!.clearFormData()
        mWeb!!.clearView()
        mWeb!!.removeAllViews()
        try {
            mWeb!!.destroy()
        } catch (e: Exception) {
        }
    }

    override fun finish() {
        val view = window.decorView as ViewGroup
        view.removeAllViews()
        super.finish()
    }


    /** Instantiate the interface and set the context.  */
    class WebAppInterface(private val mContext: Context) {
        /**
         * @description：android调用js无参函数
         */
        @JavascriptInterface
        fun androidCallJs() {
            Log.e(TAG, "androidCallJs: ====>>aaa")
        }

        /**
         * @description：android调用js带参函数
         */
        @JavascriptInterface
        fun androidCallJsWithArgs(name: String) {
            Log.e(TAG, "androidCallJsWithArgs: ====>>aaa")

        }

        /**
         * @description：js调用android无参函数
         */
        @JavascriptInterface
        fun jsCallAndroid(): String {
            Log.e(TAG, "jsCallAndroid: ====>>aaa")
            return "jsCallAndroid"
        }

        /**
         * {"action":"award","type":"vip","reward_id":1,"exchange_code":"bea17e3a0d417165d9f2fc9932585d31"}
         * {action: "navigate",type: "record"}
         * @description：js调用android带参函数
         */
        @JavascriptInterface
        fun jsCallAndroidWithArgs(name: String): String {
//        val data=name as Data41
            Log.e(TAG, "jsCallAndroidWithArgs: ====>>aaa   " + name)

            return "jsCallAndroidWithArgs=$name"
        }


        /** Show a toast from the web page.  */
        @JavascriptInterface
        fun showToast(toast: String) {
            Log.e(TAG, "showToast: ====>>")
            CommonUtils.showToast(toast)
        }

        @JavascriptInterface
        fun openAndroid(url: String) {
            Log.e(TAG, "openAndroid: ====>>" + url)

        }

        @JavascriptInterface
        fun openWebView(url: String) {
            Log.e(TAG, "openWebView: ====>>" + url)

        }

        @JavascriptInterface
        fun closeWebView() {
            Log.e(TAG, "openWebView: ====>>")

        }

        @JavascriptInterface
        fun h5landing(): Boolean {
            Log.e(TAG, "h5landing: ====>>")
            return true
        }

        @JavascriptInterface
        fun googleLogin(callback: String) {
            Log.e(TAG, "googleLogin: ====>>" + callback)

        }

        @JavascriptInterface
        fun facebookLogin(callback: String) {

//            try {
//                (activity as YourActivity).facebookLogin(callback)
//            } catch (e: java.lang.Exception) {
//                Log.e(TAG, "window.Android.facebookLogin failure", e)
//            }
            Log.e(TAG, "facebookLogin: ====>>" + callback)

        }

        @JavascriptInterface
        fun getFcmToken(callback: String) {

            // 从 FCM API 取得装置 token, 异步操作
            // from: FirebaseMessaging.getInstance().getToken()
            // 从 FCM API 取得装置 token, 异步操作
            // from: FirebaseMessaging.getInstance().getToken()
//            val fcmToken: String = task.getResult()
//            LogUtils.d("generate fcm token={}", fcmToken)
//
//            // webview 呼叫 callback 并传回 token
//
//            // webview 呼叫 callback 并传回 token
//            webView.loadUrl(
//                java.lang.String.format(
//                    "javascript:window.%s('%s')",
//                    callback,
//                    fcmToken
//                )
//            )

            Log.e(TAG, "getfcmToken: ====>>" + callback)

        }


        @JavascriptInterface
        fun packageOrigin(): String {
            Log.e(TAG, "packageOrigin: ====>>")
            return "MJ"
        }


        @JavascriptInterface
        fun phoneType(): String {
            Log.e(TAG, "phoneType: ====>>")
            return "Android"
        }

        @JavascriptInterface
        fun eventTracker(name: String, data: String?) {

            Log.e(TAG, "eventTracker: ====>>" + name + "   :" + data)
            when (name) {
                "register" -> {
                    //https://jbet77.xyz  已验证
                    //注册

                        val adjustEvent = AdjustEvent("2j7k6z")//注册事件
                        Adjust.trackEvent(adjustEvent)

                }

                "firstDepositArrival" -> {
                    //首充
                    val adjustEvent = AdjustEvent("bz48n8")//首次充值
                    Adjust.trackEvent(adjustEvent)
                }

                "deposit" -> {
                    //充值
                    val adjustEvent = AdjustEvent("h5fyk5")//充值成功
                    Adjust.trackEvent(adjustEvent)
                }
            }
        }

    }

    /*****************下面未7-1新增方法***********************/


}